using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/****************************************************
// 功能：事件管理器 1、注册/注销监听器 2、分发事件并通知监听器 3、清除指定时间的所有监听器
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/2/21 9:52:35
*****************************************************/

/// <summary>
/// 自定义事件委托类型
/// </summary>
public delegate void MyEventHandler(params object[] objects);

public class EventDispatcher: SingletonPatternBase<EventDispatcher>
{

    private readonly Dictionary<string, MyEventHandler> listeners = new Dictionary<string, MyEventHandler>();

    /// <summary>
    /// 注册事件监听
    /// </summary>
    /// <param name="type">类型</param>
    /// <param name="handler">事件处理器（回调）</param>
    public void Register(string type, MyEventHandler handler)
    {
        if (handler == null) { return; }

        if (listeners.ContainsKey(type))
        {
            listeners[type] += handler;
        }
        else
        {
            listeners.Add(type, handler);
        }
        
    }

    /// <summary>
    /// 注销事件监听
    /// </summary>
    /// <param name="type"></param>
    /// <param name="handler"></param>
    public void UnRegister(string type, MyEventHandler handler)
    {
        if (handler == null) { return; }
        
        if (listeners.ContainsKey(type))
        {
            listeners[type] -= handler;
            if (listeners[type] == null)
            {
                listeners.Remove(type);
            }
        }
    }

    /// <summary>
    /// 派发事件，通知所有监听器
    /// </summary>
    /// <param name="type"></param>
    /// <param name="objects"></param>
    public void DispatchEvent(string type, params object[] objects)
    {
        try
        {
            // 内部的监听函数可能会报错，为了不影响后面流程，就写了一个try
            if (listeners.ContainsKey(type))
            {
                MyEventHandler handler = listeners[type];
                if (handler != null) { handler(objects); }
            }
        }
        catch (Exception e)
        {
            Debug.LogFormat("[派发事件错误]，event:{0}, Error:{1}", e.Message, e.StackTrace);
        }
    }

    /// <summary>
    /// 清除指定时间监听
    /// </summary>
    /// <param name="type"></param>
    public void ClearEvents(string type)
    {
        if (listeners.ContainsKey(type)) { listeners.Remove(type); }
    }
}
